import Koa from "koa";
import Router from "koa-router";
import Static from "koa-static";
import BodyParser from "koa-bodyparser";
import Cors from "kcors";
import allRouters from "./router";
import path from "path";
// import responseTime = require("response-time");
import { init as nsqInit } from "./proxy/nsqProxy";
import { init as redisInit } from "./proxy/redisProxy";
import { AppState, AppContext } from "./types/koaExtend";
import nw from "./middleware";
import { loadConfAndEnv } from "./store/helper";

loadConfAndEnv();

try {
  nsqInit();
  console.log(`nsq初始化成功`);
} catch (e) {
  console.error(`nsq初始化失败`, e);
}

try {
  redisInit();
  console.log(`redis初始化成功`);
} catch (e) {
  console.error(`redis初始化失败`, e);
}

const app = new Koa<AppState, AppContext>();
app.use(
  Cors({
    origin: "*",
    allowMethods: "PUT, POST, GET, DELETE, OPTIONS",
  })
);

app.use(Static(path.join(__dirname, "./static")));

// Middlewares
app.use(BodyParser());
// app.use(responseTime());
app.use(nw);

app.use(allRouters());

const port = 8103;

console.log(`listing ${port} ...`);
app.listen(port, "0.0.0.0");
